package eureka.ui.book;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eureka.domain.book.BookItem;
import eureka.domain.book.BookPicture;
import eureka.exceptions.DatabaseException;
import eureka.exceptions.ItemNotExistsException;
import eureka.service.book.IBookService;
import eureka.service.book.impl.BookService;

/**
 * Servlet implementation class ShowBOOL
 */
@WebServlet("/Books/ShowBook")
public class ShowBook extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private IBookService ibc = new BookService();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ShowBook() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String beIDstr = request.getParameter("beid");
		long beID = 0;
		BookItem bookitem = null;
		try {
			beID = Long.parseLong(beIDstr);
		} catch (NumberFormatException e) {
			response.sendError(404);
			return ;
		}
		
		try {
			bookitem = ibc.getBookByBeID(beID);
		} catch (ItemNotExistsException e1) {
			response.sendError(404);
			return ;
		} catch (DatabaseException e2) {
			response.sendError(500);
			return ;
		}
		
		String mode = request.getParameter("mode");

		if ("ajax".equalsIgnoreCase(mode)) // AJAX mode
		{

			String ajaxstr = bookitem.toJSONString();

			out.println(ajaxstr);

			return;
		}

		List<BookPicture> bookpics = null;
		try {
			bookpics = ibc.getBookPicturesByBeID(beID);
		} catch (DatabaseException e) {
			response.sendError(500);
			return ;
		}
		
		request.setAttribute("bookitem", bookitem);
		request.setAttribute("bookpics", bookpics);
		request.setAttribute("bookpics_count", bookpics.size());
		
		request.getRequestDispatcher("showbook.jsp").forward(request,
				response);

	}

}
